package com.znsd.exam.controllor;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.znsd.entitys.ExamChooseInfo;
import com.znsd.entitys.ExamHistoryPaper;
import com.znsd.entitys.ExamPaperInfo;
import com.znsd.entitys.ExamSubjectMiddleInfo;
import com.znsd.entitys.Subjectinfo;
import com.znsd.entitys.Users;
import com.znsd.exam.service.ExamChooseInfoService;
import com.znsd.exam.service.ExamHistoryPaperService;
import com.znsd.exam.service.ExamPlanService;
import com.znsd.exam.service.SpecialtyService;
import com.znsd.exam.service.SubjectService;
import com.znsd.exam.service.UserServicePan;

@Controller
public class StudentControllor {

	private Logger logger = Logger.getLogger(StudentControllor.class);

	private ExamPaperInfo examPaper = new ExamPaperInfo();
	private ExamChooseInfo examChoose = new ExamChooseInfo();
	private Users student = new Users();
	private ExamSubjectMiddleInfo esm = new ExamSubjectMiddleInfo();
	@Autowired
	private ExamChooseInfoService examChooseInfoService;
	@Autowired
	private ExamPlanService examPlanInfoService;
	@Autowired
	private ExamHistoryPaperService examHistoryPaperService;
	@Autowired
	private SpecialtyService specialtyService;
	@Autowired
	private UserServicePan userService;
	@Autowired
	private SubjectService subjectService;

	@RequestMapping("/review")
	public ModelAndView reViewExam(@RequestParam("studentId") Integer studentId,
			@RequestParam("examPaperId") Integer examPaperId, @RequestParam("score") Integer score,
			@RequestParam("examPaperName") String examPaperName,
			@RequestParam(value = "specialty_name", required = false) String user_username)
			throws UnsupportedEncodingException {
		ModelAndView model = new ModelAndView();
		if (studentId == null) {
			model.addObject("error", "请先登录后再操作");
			model.setViewName("error");
			return model;
		} else {
			List<Integer> subjectList=new ArrayList<>();
			// 获取当前试卷的试题集合 -- 前台判断需要
			examPaper.setExamPaperId(examPaperId);
			esm.setExamPaper(examPaper);
			List<ExamSubjectMiddleInfo> esms = specialtyService.getExamPaperWithSubject(esm);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("studentId", studentId);
			map.put("examPaperId", examPaperId);
			for (int i = 0; i < esms.size(); i++) {
				Subjectinfo subjectinfo = subjectService.getSubjectWithId(esms.get(i).getSubject().getSubjectId());
				if(subjectinfo.getSubjectType()>1) {
					subjectList.add(esms.get(i).getSubject().getSubjectId());
				}
			}
			// 获取当前回顾试卷 试题、选择答案 信息
			List<ExamChooseInfo> reviews = examChooseInfoService.getChooseInfoWithExamSubject(map);
			for (int i = 0; i < subjectList.size(); i++) {
				for (int j = 0; j < reviews.size(); j++) {
					if(subjectList.get(i)==reviews.get(j).getSubject().getSubjectId()) {
						if(j+1<reviews.size()&&reviews.get(j+1).getSubject().getSubjectId()==subjectList.get(i)) {
 							reviews.get(j).setChooseResult(reviews.get(j).getChooseResult()+","+reviews.get(j+1).getChooseResult());
							if(j+2>=reviews.size()||j+2<reviews.size()&&reviews.get(j+2).getSubject().getSubjectId()!=subjectList.get(i)) {
								reviews.remove(j+1);
							}
						}
						if(j+2<reviews.size()&&reviews.get(j+2).getSubject().getSubjectId()==subjectList.get(i)) {
							reviews.get(j).setChooseResult(reviews.get(j).getChooseResult()+","+reviews.get(j+2).getChooseResult());
							if(j+3>=reviews.size()||j+3<reviews.size()&&reviews.get(j+3).getSubject().getSubjectId()!=subjectList.get(i)) {
								reviews.remove(j+1);
								reviews.remove(j+2);
							}
						}
						if(j+3<reviews.size()&&reviews.get(j+3).getSubject().getSubjectId()==subjectList.get(i)) {
							reviews.get(j).setChooseResult(reviews.get(j).getChooseResult()+","+reviews.get(j+3).getChooseResult());
							if(j+3<reviews.size()&&reviews.get(j+3).getSubject().getSubjectId()!=subjectList.get(i)) {
								reviews.remove(j+1);
								reviews.remove(j+2);
								reviews.remove(j+3);
							}
						}
					}
				}
			}
			logger.info("学生 " + studentId + " 回顾试卷 " + examPaperId + " 试题数量 " + reviews.size());
			// 设置试卷名称、试卷总分
			model.addObject("examPaperName", examPaperName);
			model.addObject("score", score);

			model.setViewName("reception/review");
			model.addObject("views", reviews);

			model.addObject("esms", esms);
			if (user_username != null)
				model.addObject("studentName", user_username);

			return model;
		}
	}
	
	
	@RequestMapping(value="studentLogin",method = RequestMethod.GET)
	public String stuLogin() {
		return "reception/index";
	}
	@RequestMapping(value="studentHome",method = RequestMethod.GET)
	public String stuLogin2() {
		return "reception/home";
	}
	@RequestMapping(value="reception/login",method = RequestMethod.GET)
	public String stuLogin3() {
		return "reception/login";
	}
	@RequestMapping(value="/studentLogin", method=RequestMethod.POST)
	public ModelAndView studentLogin(@RequestParam("user_username")String user_username,@RequestParam("user_password")String user_password, HttpServletRequest request) {
		Map<String,Object> map=new HashMap<>();
		ModelAndView model = new ModelAndView();
		map.put("user_username", user_username);
		map.put("user_password", user_password);
		Users loginStudent = userService.getStudentByAccountAndPwd(map);
		if(loginStudent!=null) {
			logger.info("学生 "+loginStudent+" 有效登录");
			request.getSession().setAttribute("loginStudent", loginStudent);
			model.setViewName("reception/suc");
			model.addObject("success","登录成功");
		}else {
			model.setViewName("reception/login");
			model.addObject("msg", "登录失败，请检查账号或密码是否正确，无班级的账号不能进行登录，请等待老师分班！");
		}
		return model;
	}
	@RequestMapping(value="/reception/studentLogin", method=RequestMethod.POST)
	public ModelAndView studentLogin2(@RequestParam("user_username")String user_username,@RequestParam("user_password")String user_password, HttpServletRequest request) {
		Map<String,Object> map=new HashMap<>();
		ModelAndView model = new ModelAndView();
		map.put("user_username", user_username);
		map.put("user_password", user_password);
		Users loginStudent = userService.getStudentByAccountAndPwd(map);
		if(loginStudent!=null) {
			logger.info("学生 "+loginStudent+" 有效登录");
			request.getSession().setAttribute("loginStudent", loginStudent);
			model.setViewName("reception/suc");
			model.addObject("success","登录成功");
		}else {
			model.setViewName("reception/login");
			model.addObject("msg", "登录失败，请检查账号或密码是否正确，无班级的账号不能进行登录，请等待老师分班！");
		}
		return model;
	}
	/**
	 * 退出登录
	 * @param session
	 * @return
	 */
	@RequestMapping("/exit")
	public String studentClearLogin(HttpSession session) {
		Users studnet = (Users) session.getAttribute("loginStudent");
		logger.info("学生 "+studnet.getUser_username()+", 编号 "+studnet.getUser_id()+" 退出登录");
		session.removeAttribute("loginStudent");
		
		return "redirect:studentLogin";
	}
	
	/**
	 * 学生查看自己信息
	 * 
	 * @param studentId
	 * @return
	 */
	
	  @RequestMapping("/self/{studentId}") 
	  public ModelAndView selfInfo(@PathVariable("studentId") Integer studentId) { 
		  Users stu = userService.getStudentById(studentId);
		  ModelAndView model = new ModelAndView();
		  model.setViewName("/reception/self"); model.addObject("self", stu);
		  return model; 
	  }
	  /**
	 * 获取学生历史考试记录
	 * @param studentId 学生编号
	 * @return
	 */
	@RequestMapping("/history/{studentId}")
	public ModelAndView getExamHistoryInfo(@PathVariable("studentId") Integer studentId) {
		ModelAndView model = new ModelAndView();
		
		if (studentId == null) {
			logger.error("学生编号 为空");
			model.setViewName("error");
			return model;
		}
		logger.info("学生 "+studentId+" 获取考试历史记录");
		//获取历史考试信息记录集合
		List<ExamHistoryPaper> ehps = examHistoryPaperService.getExamHistoryToStudent(studentId);
		model.addObject("ehps", ehps);
		model.setViewName("/reception/examHistory");
		
		return model;
	}
	/**
	 * 学生进入考试
	 * @param classId 班级编号
	 * @param examPaperId 试卷编号
	 * @param studentId 考生编号
	 * @param examTime 考试时间
	 * @param beginTime 考试开始时间
	 * @param gradeId 年级编号
	 * @param session
	 * @return
	 */
	@RequestMapping("/begin")
	public ModelAndView beginExam(
			@RequestParam("clazz_id") Integer classId,
			@RequestParam("examPaperId") Integer examPaperId,
			@RequestParam(value="user_id", required=false) Integer studentId,
			@RequestParam("examTime") Integer examTime,
			@RequestParam("beginTime") String beginTime,
			HttpSession session) {
		ModelAndView model = new ModelAndView();
		
		/*
		 * 查询该考试当前进入的试卷是否已经在历史记录中存在
		 * 如果存在，则不能再次进入考试； 反之进入考试
		 */
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("studentId", studentId);
		map.put("examPaperId", examPaperId);
		int count = examHistoryPaperService.getHistoryInfoWithIds(map);
		if(session.getAttribute("loginStudent") == null) {
			model.addObject("error", "请先登录后再操作");
			model.setViewName("error");
			return model;
		} else if (count >= 1) {
			model.addObject("error", "你已经考试过了");
			model.setViewName("error");
			return model;
		} else {			
			logger.info("学生 "+studentId+" 进入考试 班级 "+classId+" 试卷 "+examPaperId);
			model.setViewName("/reception/exam");
			
			ExamPaperInfo examPaper = new ExamPaperInfo();
			examPaper.setExamPaperId(examPaperId);
			esm.setExamPaper(examPaper);
			//获取试卷 试题集合
			List<ExamSubjectMiddleInfo> esms = specialtyService.getExamPaperWithSubject(esm);
			logger.info("考试试题总量 "+esms.size());
			
			//获取当前考生在当前试卷中已选答案记录
			Map<String, Object> choosedMap = new HashMap<String, Object>();
			choosedMap.put("studentId", studentId);
			choosedMap.put("examPaperId", examPaperId);
			List<ExamChooseInfo> chooses = examChooseInfoService.getChooseInfoWithSumScore(choosedMap); 
			if (chooses == null || chooses.size() == 0) {
				model.addObject("chooses", null);
			} else {
				model.addObject("chooses", chooses);				
			}
			
			
			model.addObject("esms", esms);
			model.addObject("sumSubject", esms.size());
			model.addObject("examPaperId", examPaperId);
			model.addObject("examTime", examTime);
			model.addObject("beginTime", beginTime);
			model.addObject("classId", classId);
			
			return model;
		}
	}
	/**
	 * 记录考生考试选择答案
	 * @param studentId 考生编号
	 * @param examPaperId 考试试卷编号
	 * @param subjectId 当前选择试题编号
	 * @param index 前台控制索引
	 * @param chooseAswer 选择答案
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/choose", method=RequestMethod.POST)
	public void examChooseHandler(
			@RequestParam("studentId") Integer studentId,
			@RequestParam("examPaperId") Integer examPaperId,
			@RequestParam("subjectId") Integer subjectId,
			@RequestParam(value="index", required=false) Integer index,
			@RequestParam("chooseAswer") String chooseAswer,
			HttpServletResponse response) throws IOException {
		logger.info("考生 "+studentId+" 在试卷 "+examPaperId+" 中试题 "+subjectId+" 选择了答案 "+chooseAswer+" 序号 "+index);
		Subjectinfo subject = subjectService.getSubjectWithId(subjectId);
		//判断该考生是否已经选择过该试题
		int a=0;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("studentId", studentId);
		map.put("examPaperId", examPaperId);
		map.put("subjectId", subjectId);
		List<ExamChooseInfo> examChooseList = null;
		if(subject.getSubjectType()<2) {
			examChoose = examChooseInfoService.getChooseWithIds(map);
		}else {
			examChooseList=examChooseInfoService.getChooseWithIdsList(map);
		}
		logger.info("考生是否选择过试题 "+subjectId+" "+examChoose+" (NULL-否)");
		if (examChooseList!=null&&examChooseList.size()<1||examChoose == null) {
			logger.info("考生 "+studentId+" 尚未选择试题 "+subjectId+" 添加选择记录 答案 "+chooseAswer);
			map.put("chooseResult", chooseAswer);
			/** 添加选择记录 */
			examChooseInfoService.addChoose(map);
		} else if (examChooseList!=null&&examChooseList.size()>0||examChoose.getChooseId() != null && examChoose != null) {
			logger.info("考生 "+studentId+" 已经选择试题 "+subjectId+" 修改选择记录 答案 "+examChoose.getChooseResult()+" 更新为 "+chooseAswer);
			/*
			 * 如果选择了和上次相同的答案，则不做修改操作
			 * 优化 -- 前台判断选择了相同答案则不发出请求
			 */
			if(examChooseList!=null&&examChooseList.size()>0) {
				for (ExamChooseInfo examChooseInfo : examChooseList) {
					if(chooseAswer.equals(examChooseInfo.getChooseResult())) {
						a=1;
					}
				}
				if(a==0) {
					map.put("chooseResult", chooseAswer);
					examChooseInfoService.addChoose(map);
				}
			}else {
				if(!chooseAswer.equals(examChoose.getChooseResult())) {
					examChoose.setChooseResult(chooseAswer);
					/** 当前选择答案和之前选择答案不同 修改答案记录 */
					examChooseInfoService.updateChooseWithIds(examChoose);
				}else {
					logger.info("考生选择了相同答案，不做修改操作");
				}
			}
		} else {
			response.getWriter().print("f");
			return;
		}
		
		response.getWriter().print("t");
	}
	
	//学生提交试卷
	@RequestMapping(value="/submit", method={RequestMethod.POST, RequestMethod.GET})
	public String examSubmit(
			@RequestParam("studentId") Integer studentId,
			@RequestParam("examPaperId") Integer examPaperId,
			@RequestParam("classId") Integer classId) {
		logger.info("学生 "+studentId+" 提交了试卷 "+examPaperId);
		int subjectCount=0;
		int subjectCount2=0;
		//获取当前学生当前试卷所选择的全部答案
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("studentId", studentId);
		map.put("examPaperId", examPaperId);
		List<ExamChooseInfo> chooses = examChooseInfoService.getChooseInfoWithSumScore(map);
		logger.info("学生 "+studentId+" 共选择了 "+chooses.size()+" 道题");
		
		//总分记录
		int sumScore = 0;
		for (ExamChooseInfo choose : chooses) {
			Subjectinfo subject = subjectService.getSubjectWithId(choose.getSubject().getSubjectId());
			if(subject.getSubjectType()<2) {
				String chooseResult = choose.getChooseResult();
				String rightResult = subject.getRightResult();
				
				if (chooseResult.equals(rightResult)) {	//答案正确
					sumScore += subject.getSubjectScore();
					logger.info("学生 "+studentId+" 第 "+subject.getSubjectId()+" 选择正确答案 "+chooseResult+" 当前总分 "+sumScore);
				} else {
					logger.info("学生 "+studentId+" 第 "+subject.getSubjectId()+" 答案选择错误 "+chooseResult+" 正确答案为 "+rightResult+" 当前总分 "+sumScore);				
				}
			}else {
				if(choose.getSubject().getSubjectId()!=subjectCount) {
					Subjectinfo subjectinfo = subjectService.getSubjectWithId(choose.getSubject().getSubjectId());
					List<ExamChooseInfo> subjectIdList = examChooseInfoService.getChooseWithSubjectIdList(choose.getSubject().getSubjectId());
					if(subjectinfo!=null&&subjectIdList!=null) {
						if(subjectinfo.getRightResult().split(",").length==subjectIdList.size()) {
							for (int i = 0; i < subjectinfo.getRightResult().split(",").length; i++) {
								if(subjectinfo.getRightResult().contains(subjectIdList.get(i).getChooseResult())) {
									subjectCount2++;
								}
							}
							if(subjectCount2==subjectIdList.size()) {
								sumScore+=subjectinfo.getSubjectScore();
								subjectCount2=0;
							}else {
								subjectCount2=0;
							}
						}
					}
				}
				subjectCount=choose.getSubject().getSubjectId();
			}
		}
		
		
		/*
		 * 首先判断当前记录是否已经添加过
		 * 防止当前学生点击提交后，系统倒计时再次进行提交
		 */
		int count = examHistoryPaperService.getHistoryInfoWithIds(map);
		
		if (count == 0) {
			//添加到历史记录
			map.put("examScore", sumScore);
			int row = examHistoryPaperService.addExamHistory(map);
			logger.info("学生 "+studentId+" 提交的试卷 "+examPaperId+" 已成功处理，并添加到历史记录中");
		}
		
		return "redirect:student/examSuc?examScore="+sumScore+"&clazz_id="+classId+"&studentId="+studentId;
	}
	@RequestMapping(value="/student/examSuc",method = RequestMethod.GET)
	public ModelAndView examSuc(Integer clazz_id,
			Integer studentId,
			Integer examScore) {
		
		ModelAndView model = new ModelAndView();
		model.setViewName("reception/examSuc");
		model.addObject("clazz_id", clazz_id);
		model.addObject("studentId",studentId);
		model.addObject("examScore",examScore);
		return model;
	}
}